#!/bin/sh

# Automated script to change XOriginPolicy value in LibreWolf for fixing video
# playback issues on certain websites. Note: This is for Appimages only.
# Details: https://freehub.space/item/62631183-9b48-4625-836b-1f383a0eb7bd
#
# Usage:
# 1. Download the latest LibreWolf Appimage from:
#    https://gitlab.com/librewolf-community/browser/linux/-/releases
# 2. Run this script with the appimage file as the parameter:
#    bash librewolf-xorigin.sh path/to/LibreWolf-*.Appimage
# 3. When it's done and asks to overwrite the original Appimage file, enter y

if [ -f "$1" ]; then
	# Prepare variables
	tmppath="/tmp/lw-xorigin"
	appimage_filepath="$(realpath $1)"
	appimage_filename="$(basename $1)"

	# Prepare /tmp
	mkdir -p "$tmppath"
	cp "$appimage_filepath" "$tmppath/$appimage_filename"
	cd "$tmppath"
	chmod +x "$appimage_filename"
	"./$appimage_filename" --appimage-extract

	# Change the value in librewolf.cfg
	sed -i 's/"network.http.referer.XOriginPolicy", 1/"network.http.referer.XOriginPolicy", 0/' squashfs-root/librewolf.cfg

	# Create the Appimage back
	if [ -x "$(command -v appimagetool)" ]; then
		appimagetool -v squashfs-root
	else
		curl -LO https://github.com/AppImage/AppImageKit/releases/download/12/appimagetool-x86_64.AppImage | wget https://github.com/AppImage/AppImageKit/releases/download/12/appimagetool-x86_64.AppImage
		chmod +x appimagetool-x86_64.AppImage
		./appimagetool-x86_64.AppImage -v squashfs-root "$appimage_filename"
	fi

	# Ask to overwrite the original Appimage with the modified one
	echo "Modified version of the Appimage has been created. Please enter \"y\" when asked to overwrite to apply the changes to $appimage_filepath."
	cp -i "$appimage_filename" "$appimage_filepath"

	# We're done, so delete the temporary directory
	rm -rf "$tmppath"
else
	# The file doesn't exist...
	# because there are no file with the input name
	if [ -x "$1" ]; then
		echo "The file $1 doesn't exist. Please provide a valid appimage file as parameter."
	# because there are no filename given
	else
		echo "No filename given. Please provide the appimage file as parameter."
	fi
fi
